package com.googlecode.tracey.headers.log4j;

import com.googlecode.tracey.id.TraceyId;
import org.apache.log4j.MDC;

import static com.googlecode.tracey.headers.Headers.TRACEY_ID_HEADER_NAME;

public class TraceyLog4jHeaders {

    public static void clearMdc() {
        MDC.remove(TRACEY_ID_HEADER_NAME);
    }
    public static void setIntoMdc() {
        if(TraceyId.hasValue()) {
            MDC.put(TRACEY_ID_HEADER_NAME, TraceyId.get().value());
        }
    }

    public static void usingTraceyId(Runnable whatToDo) {
        setIntoMdc();
        try {
            whatToDo.run();
        } finally {
            clearMdc();
        }
    }

    public static void usingTraceyId(Runnable whatToDo, Runnable whatToDoFinally) {
        setIntoMdc();
        try {
            whatToDo.run();
        } finally {
            whatToDoFinally.run();
        }
    }
}
